<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="120px">

      <el-form-item prop="carrierId">
        <el-select v-model="queryParams.carrierId" placeholder="承运商" clearable size="small">
          <el-option
            v-for="item in carrierOptions"
            :key="item.id"
            :label="item.carrierName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

<el-form-item prop="fileNo">
        <el-input
          v-model="queryParams.fileNo"
          placeholder="请输入档案编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item prop="personName">
        <el-input
          v-model="queryParams.personName"
          placeholder="姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item prop="driverCode">
        <el-input
          v-model="queryParams.driverCode"
          placeholder="驾驶证号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>





      <el-form-item>
        <el-date-picker
          v-model="daterangeReceiveDateFirst"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="初次领证日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>



      <el-form-item prop="validPeriodFrom">
        <el-date-picker clearable size="small"
          v-model="queryParams.validPeriodFrom"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="驾照有效期起">
        </el-date-picker>
      </el-form-item>


      <el-form-item prop="validPeriodTo">
        <el-date-picker clearable size="small"
          v-model="queryParams.validPeriodTo"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="驾照有效期止">
        </el-date-picker>
      </el-form-item>

      <!-- <el-form-item label="删除标识" prop="delFlag">
        <el-select v-model="queryParams.delFlag" placeholder="请选择删除标识" clearable size="small">
          <el-option
            v-for="dict in dict.type.sys_del_flag"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['tms:driver:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['tms:driver:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tms:driver:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['tms:driver:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="driverList" @selection-change="handleSelectionChange" border stripe>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="档案编号" align="center" prop="fileNo" min-width="160" fixed="left">
            <template slot-scope="scope">
              <el-link type="primary" @click="handleInfo(scope.row)">{{scope.row.fileNo}}</el-link>
            </template>
          </el-table-column>
      <el-table-column label="姓名" align="center" prop="personName" min-width="100" fixed="left"/>
      <!-- <el-table-column label="性别" align="center" prop="sex">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column> -->
      <el-table-column label="驾驶证号" align="center" prop="driverCode" min-width="160" fixed="left"/>
      <el-table-column label="准驾车型" align="center" prop="vehicleClass">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.tms_vehicle_class" :value="scope.row.vehicleClass ? scope.row.vehicleClass.split(',') : []"/>
        </template>
      </el-table-column>
      <el-table-column label="初次领证日期" align="center" prop="receiveDateFirst" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.receiveDateFirst, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="发证机关" align="center" prop="issuingOrganizations" /> -->
      <el-table-column label="驾照有效期起" align="center" prop="validPeriodFrom" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.validPeriodFrom, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="驾照有效期止" align="center" prop="validPeriodTo" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.validPeriodTo, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="驾驶证图片" align="center" prop="driverImg" width="180">
        <template slot-scope="scope" v-if="scope.row.driverImg">
            <el-image :src="scope.row.driverImg" :preview-src-list="[scope.row.driverImg]" style="width: 120px; height: 60px;"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="驾驶证副页图片" align="center" prop="driverSecondImg" width="180">
        <template slot-scope="scope" v-if="scope.row.driverSecondImg">
            <el-image :src="scope.row.driverSecondImg" :preview-src-list="[scope.row.driverSecondImg]" style="width: 120px; height: 60px;"></el-image>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="备注" align="center" prop="remark" />      -->
      <el-table-column label="承运商" align="center" prop="carrierName"  min-width="160" fixed="right"/>
      <!-- <el-table-column label="删除标识" align="center" prop="delFlag">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_del_flag" :value="scope.row.delFlag"/>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['tms:driver:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['tms:driver:remove']"
          >删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改司机对话框 -->

    <el-dialog :title="title" :visible.sync="open" width="1100px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">

        <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item label="承运商" prop="carrierId">
              <el-select v-model="form.carrierId" placeholder="请选择承运商" :disabled="!form.isShow">
                <el-option
                  v-for="item in carrierOptions"
                  :key="item.id"
                  :label="item.nickName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="姓名" prop="personName">
              <el-input v-model="form.personName" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">

            <el-form-item label="性别" prop="sex">
              <el-select v-model="form.sex" placeholder="请选择性别">
                <el-option
                  v-for="dict in dict.type.sys_user_sex"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item label="驾驶证号" prop="driverCode">
              <el-input v-model="form.driverCode" placeholder="请输入驾驶证号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="准驾车型" prop="vehicleClass">
              <!-- <el-checkbox-group v-model="form.vehicleClass">
                <el-checkbox
                  v-for="dict in dict.type.tms_vehicle_class"
                  :key="dict.value"
                  :label="dict.value">
                  {{dict.label}}
                </el-checkbox>
              </el-checkbox-group> -->
              <el-select v-model="form.vehicleClass" multiple>
                <el-option v-for="dict in dict.type.tms_vehicle_class"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
                />
              </el-select>
            </el-form-item>

          </el-col>

          <el-col :span="8">
            <el-form-item label="发证机关" prop="issuingOrganizations">
              <el-input v-model="form.issuingOrganizations" placeholder="请输入发证机关" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="8">
             <el-form-item label="档案编号" prop="fileNo">
              <el-input v-model="form.fileNo" placeholder="请输入档案编号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="初次领证日期" prop="receiveDateFirst">
              <el-date-picker clearable
                v-model="form.receiveDateFirst"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择初次领证日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="驾照有效期起" prop="validPeriodFrom">
              <el-date-picker clearable
                v-model="form.validPeriodFrom"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择驾照有效期起">
              </el-date-picker>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item label="驾照有效期止" prop="validPeriodTo">
              <el-date-picker clearable
                v-model="form.validPeriodTo"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择驾照有效期止">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="驾驶证图片" prop="driverImg">
              <image-upload v-model="form.driverImg" :limit="1"></image-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="驾驶证副页图片" prop="driverSecondImg">
              <image-upload v-model="form.driverSecondImg" :limit="1"></image-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15" v-if="!form.userId">
          <el-col>
            <el-form-item label="账号信息"></el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15" v-if="!form.userId">
          <el-col :span="8">
            <el-form-item label="账号" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户账号" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { initBean,listDriver, getDriver, delDriver, addDriver, updateDriver } from "@/api/tms/driver";
import {listCarrier} from '@/api/tms/carrier';
import {listUser} from '@/api/system/user';
export default {
  name: "Driver",
  dicts: ['sys_del_flag', 'tms_vehicle_class','sys_user_sex'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 预览列表图片
      previewListResource: true,
      // 总条数
      total: 0,
      // 司机表格数据
      driverList: [],
      carrierOptions:[],
      userOptions:[],
      // 默认密码
      initPassword: undefined,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeReceiveDateFirst: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        carrierId: undefined,
        userId: undefined,
        personName: undefined,
        vehicleClass: undefined,
        driverCode: undefined,
        fileNo: undefined,
        receiveDateFirst: undefined,
        validPeriodFrom: undefined,
        validPeriodTo: undefined,
        delFlag: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        carrierId: [
          { required: true, message: "承运商不能为空", trigger: "blur" }
        ],
        // sex: [
        //   { required: true, message: "性别不能为空", trigger: "blur" }
        // ],
        personName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        // vehicleClass: [
        //   { required: true, message: "准驾车型不能为空", trigger: "blur" }
        // ],
        driverCode: [
          { required: true, message: "驾驶证号不能为空", trigger: "blur" }
        ],
        // fileNo: [
        //   { required: true, message: "档案编号不能为空", trigger: "blur" }
        // ],
        // receiveDateFirst: [
        //   { required: true, message: "初次领证日期不能为空", trigger: "blur" }
        // ],
        // issuingOrganizations: [
        //   { required: true, message: "发证机关不能为空", trigger: "blur" }
        // ],
        // validPeriodFrom: [
        //   { required: true, message: "驾照有效期起不能为空", trigger: "blur" }
        // ],
        // validPeriodTo: [
        //   { required: true, message: "驾照有效期止不能为空", trigger: "blur" }
        // ],
        // driverImg: [
        //   { required: true, message: "驾驶证图片不能为空", trigger: "blur" }
        // ],
        // driverSecondImg: [
        //   { required: true, message: "驾驶证副页图片不能为空", trigger: "blur" }
        // ],
        userName: [
          { required: true, message: "用户账号不能为空", trigger: "blur" }
        ],
        password: [
        { required: true, message: "用户密码不能为空", trigger: "blur" },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getCarrier();
    this.getUser();
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    /** 查询司机列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeReceiveDateFirst && '' != this.daterangeReceiveDateFirst) {
        this.queryParams.params["beginReceiveDateFirst"] = this.daterangeReceiveDateFirst[0];
        this.queryParams.params["endReceiveDateFirst"] = this.daterangeReceiveDateFirst[1];
      }
      listDriver(this.queryParams).then(response => {
        this.driverList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /**查询承运商列表 */
    getCarrier(){
      listCarrier().then(response=>{
        this.carrierOptions = response.rows;
      })
    },
    handleInfo(row){
         const id = row.id;
         this.$router.push({
           path: '/tms/drivers/detail/' + id,
           query: {
             pageNum: this.queryParams.pageNum
           }
         });
      },
    /**查询用户列表 */
    getUser(){
      listUser().then(response=>{
        this.userOptions = response.rows;
      })
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        carrierId: undefined,
        userId: undefined,
        personName: undefined,
        sex: undefined,
        vehicleClass: [],
        driverCode: undefined,
        fileNo: undefined,
        receiveDateFirst: undefined,
        issuingOrganizations: undefined,
        validPeriodFrom: undefined,
        validPeriodTo: undefined,
        driverImg: undefined,
        driverSecondImg: undefined,
        remark: undefined,
        delFlag: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeReceiveDateFirst = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      initBean().then(response=>{
        this.form = response.data;
        this.title = "添加司机";
        this.form.password = this.initPassword;
        this.open = true;
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getDriver(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.form.vehicleClass = this.form.vehicleClass.split(",");
        this.open = true;
        this.title = "修改司机";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          this.form.vehicleClass = this.form.vehicleClass.join(",");
          if (this.form.id != null) {
            updateDriver(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addDriver(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除司机编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delDriver(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('tms/driver/export', {
        ...this.queryParams
      }, `driver_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
